package editor;

import java.awt.Container;
import java.io.*;

import javax.swing.JFileChooser;

import loading.ImageLoader;

public class Tile 
{
	private ImageLoader img;
	private int key;
	private boolean isOccupied;
	
	private String tilesetName;
	
	public Tile( ImageLoader img, String tileset, boolean occupied )
	{
		this.img = img;
		tilesetName = tileset;
		
		File f = null;
		int i;
		for( i = 0; i < 256; i++ )
		{
			f = new File( "Tiles/" + tilesetName + "/tile" + i + ".txt" );
			if( !f.exists() )
			{
				break;
			}
		}
		
		key = i;
		
		this.isOccupied = occupied;
	}
	
	public Tile( ImageLoader img, String tileset, int key, boolean occupied  )
	{
		this.img = img;
		tilesetName = tileset;
		this.key = key;
		this.isOccupied = occupied;
	}
	
	public boolean isOccupied()
	{
		return isOccupied;
	}
	
	public static Tile load( String filename )
	{
		File f = new File( filename );
	
		try 
		{
			FileReader stream = new FileReader( f );
			BufferedReader buf = new BufferedReader( stream );

			int key = Integer.valueOf( buf.readLine() );
		
			String name = buf.readLine();
		
			String location = buf.readLine();
			
			String occup = buf.readLine();
			boolean occupied = occup.equals( "True" );
		
			return new Tile( new ImageLoader( location ), name, key, occupied );
		
		} 
		catch ( FileNotFoundException e ) 
		{
			e.printStackTrace();
		} 
		catch ( IOException e ) 
		{
			e.printStackTrace();
		}
		
		return null;
	}
	
	public static Tile load( Container frame )
	{
		JFileChooser fc = new JFileChooser();
		fc.setCurrentDirectory( new File( "C:/Documents and Settings/Owner/Desktop/Projects/Level Editor/Tiles" ) );
		int returnVal = fc.showOpenDialog( frame );
		
		if( returnVal == JFileChooser.APPROVE_OPTION )
		{
			load( fc.getSelectedFile().getAbsolutePath() );
		}
			
		return null;
	}
	
	public String save()
	{
		File f = new File( "Tiles/" + tilesetName );
		if( !f.exists() )
		{
			f.mkdir();
		}
		
		f = new File( "Tiles/" + tilesetName + "/tile" + key + ".txt" );
		
		try 
		{ 
			f.createNewFile();
			BufferedWriter buf = new BufferedWriter( new FileWriter( f.getAbsolutePath() ) );
			
			buf.write( "" + key + "\n" + tilesetName + "\n" + img.getFilename() + "\n" );
			
			if( isOccupied )
				buf.write( "True" );
			else
				buf.write( "False" );
			
			buf.close();
		} 
		catch ( FileNotFoundException err ) 
		{
			err.printStackTrace();
		} 
		catch ( IOException err ) 
		{
			err.printStackTrace();
		}
	
		return f.getAbsolutePath();
	}
	
	public ImageLoader getImage()
	{
		return img;
	}
	
	public String getTilesetName()
	{
		return tilesetName;
	}
	
	public int getKey()
	{
		return key;
	}
}
